package cat.joronya.supermanager.service.htmlcleanerImpl;

import java.util.Hashtable;
import java.util.List;

import org.htmlcleaner.ContentNode;
import org.htmlcleaner.HtmlCleaner;
import org.htmlcleaner.TagNode;

import android.util.Log;

import cat.joronya.supermanager.Supermanager;
import cat.joronya.supermanager.service.DayMatchesParser;

public class DayMatchesParserImpl implements DayMatchesParser
{
	// matches XPATH
	private static final String MATCHES_XPATH = "//table[@class='resultados']";
	
	// matches hashtable
	private Hashtable<String, String> matches = new Hashtable<String, String>();

	public long parse(String html) throws Exception 
	{
		long start = System.nanoTime();

		HtmlCleaner cleaner = new HtmlCleaner();
		TagNode node = cleaner.clean(html);

		// search the matches
		Object[] tables = node.evaluateXPath(MATCHES_XPATH);

		// some error and no match found
		if( tables.length == 0 )
			return 0;

		TagNode table = (TagNode)tables[0];
		TagNode tbody = table.getChildTags()[0];

		// every tr has a match
		List trs = tbody.getChildren();
		for( int i=2; i<trs.size(); i++ )
		{
			TagNode tr = (TagNode)trs.get(i);
			List tds = tr.getChildren();

			// home team
			TagNode homeTeamTd = (TagNode)tds.get(0);
			List homeTeamTdChilds = homeTeamTd.getChildren();
			String homeTeam;
			if( homeTeamTdChilds.get(0) instanceof ContentNode )
			{
				homeTeam = ((ContentNode)homeTeamTdChilds.get(0)).toString();
				homeTeam = homeTeam.replace(" |", "");
			}
			else
			{
				TagNode aHomeTeam = (TagNode)homeTeamTdChilds.get(0);
				List anchorChilds = aHomeTeam.getChildren();
				homeTeam = ((ContentNode)anchorChilds.get(0)).toString();
			}
			homeTeam = teamNameToAcronim.get(homeTeam);

			// vs team
			TagNode vsTeamTd = (TagNode)tds.get(1);
			List vsTeamTdChilds = vsTeamTd.getChildren();
			String vsTeam;
			if( vsTeamTdChilds.get(0) instanceof ContentNode )
			{
				vsTeam = ((ContentNode)vsTeamTdChilds.get(0)).toString();
			}
			else
			{
				TagNode aVsTeam = (TagNode)vsTeamTdChilds.get(0);
				List anchorChilds = aVsTeam.getChildren();
				vsTeam = ((ContentNode)anchorChilds.get(0)).toString();
			}
			vsTeam = teamNameToAcronim.get(vsTeam);

			// store teams only if parsed
			if( homeTeam != null && vsTeam != null && 
					!"".equals(homeTeam) && !"".equals(vsTeam) )
			{
				Log.d(Supermanager.TAG,"DayMatchesParser.parse found match: "+homeTeam+" vs "+vsTeam);
				matches.put(homeTeam, vsTeam);
				matches.put(vsTeam, homeTeam);
			}
		}

		return System.nanoTime()-start;
	}

	public Hashtable<String, String> getDayMatches() 
	{
		return matches;
	}
}

